﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.QPZS.EPC.API.Domain.Entities;
using Wicture.QPZS.EPC.API.Repository;

namespace Wicture.QPZS.EPC.API.InvokeContextBuilders
{
    public class ServiceThrottlingBuilder : IThrottlingContextBuilder
    {
        private readonly IServiceRepository _serviceRepository;

        public ServiceThrottlingBuilder(IServiceRepository serviceRepository)
        {
            _serviceRepository = serviceRepository;
        }

        public decimal Order => 2;

        public void Build(ThrottlingContext context, object sender, ApiInvokingArgs e)
        {
            if (context.AccountId <= 0)
            {
                return;
            }
            var accountPackage = _serviceRepository.GetAccountPackage(context.AccountId);
            context.AccountPackage = accountPackage;
            if (accountPackage == null)
            {
                return;
            }
            var package = _serviceRepository.GetServicePackage(accountPackage.PackageId);
            if (package == null)
            {
                return;
            }
            context.ServicePackage = package;
            if (string.IsNullOrEmpty(context.ApiName))
            {
                return;
            }
            var definition = _serviceRepository.GetServiceDefinition(context.ApiName);
            if (definition == null)
            {
                return;
            }
            context.ServiceDefinition = definition;
            var accountApi = _serviceRepository.GetAccountPackageApis(accountPackage.Id, definition.Id);
            if (accountApi == null)
            {
                return;
            }
            context.AccountPackageApi = accountApi;
        }
    }
}
